// packageA/pages/cleanWorkHandle/cleanWorkHandle.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
const util = require('../../../utils/util');
import Base64 from '../../../utils/Base64.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    active: 2,
    steps: [
      {
        text: '订单提交',
        desc: '已确认订单信息',
        time: '2023-10-05 08:30'
      },
      {
        text: '支付完成',
        desc: '已确认订单信息\n2023-10-05 08:30',
        time: '2023-10-05 09:15'
      },
      {
        text: '正在配送',
        desc: '快递员：张三（138****5678）',
        time: '2023-10-05 10:40'
      }
    ],
    //当前用户
    user: null,
    //传参
    paramObj:null,
    //传参来的id
    id:null,
    //修改信息回显
    editInfo:{},
    //提交按钮禁用
    disabled:false,
    cleanOrderMessageReceive:[],
    mediaList: [],        // 存储选中的媒体文件
    uploadProgress: 0,    // 总体上传进度
    uploadedCount: 0,     // 已上传完成的数量
    totalCount: 0,        // 总上传数量
    showProgress: false,  // 是否显示进度条
    isUploading: false,    // 是否正在上传中
    taskImg:[],
    pendingFilesArr:[],
    type:"",
    showReasonForRejection:false,
    //审批提交禁用按钮
    disabledApprove:false,
    //
    location:null,

    showPrivacyModal: false,  // 是否已同意小程序隐私授权
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      pendingFilesArr:[],
      user: app.globalData.userInfo
    })

    if(options.paramObj){
      let paramObj=JSON.parse(options.paramObj);
      console.log('保洁工单传参');
      console.log(paramObj);
      this.setData({
        type:paramObj.type,
        paramObj: paramObj
      })

      if(paramObj.id){
        this.setData({
          id: paramObj.id
        })
        //获取修改数据
        this.getInfo();
       // this.findClearOrderMessageReceive(paramObj.projectId)
        
      }
    }
   
  },
  // 2. 用户点击官方隐私授权按钮并同意后触发
  async  handleAgreePrivacy() {
    const that = this;
    console.log(111);
    // 更新隐私授权状态，开始获取位置
    that.setData({
      showPrivacyModal: false,
    });
    await this.getLocationInfo();
  },
  // 1. 检查隐私授权和系统定位授权状态
   checkPrivacyAndAuthStatus() {
    const that = this;
    // 第一步：查询小程序隐私授权状态
    wx.getPrivacySetting({
      success: async (privacyRes) => {
        console.log("privacyRes");
        console.log(privacyRes);
      // 若用户无需隐私授权，直接调用获取位置的方法
      //errMsg: "getPrivacySetting:ok"：接口调用成功，无异常
      //privacyContractName: "《蓝茶物联网小程序隐私保护指引》"：说明你在小程序后台配置的隐私保护声明已成功生效，微信已识别到该协议；
      //needAuthorization: false：表示用户无需再进行隐私授权操作（可能是用户已主动同意过，或隐私协议无需用户二次确认）；
      if (!privacyRes.needAuthorization) {
        await this.getLocationInfo();
        return;
      }
      // 若需授权（极端场景，当前你的情况不会触发），再显示弹出层
      that.setData({ showPrivacyModal: true });
      },
      fail: () => {
        that.showError('隐私授权状态查询失败，请重试', false);
      }
    });
  },
  onClose(){
    this.setData({
      showPrivacyModal:false
    })
  },
  findClearOrderMessageReceive(projectId){
		let dataObj={
			selectFields: ['id','name','cleanLeader','cleanOrderUsers'],
      id:projectId
		}
		let param = {
      className: 'depart',
      data: dataObj
		}

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result;
        console.log('保洁工单接收人');
        console.log(result); 
        if (result!=null && result.length>0){
          if (result[0].cleanLeader != null){
            this.setData({
              cleanOrderMessageReceive:result[0].cleanOrderUsers
            })
          }
        }
      }
    }).catch((error) => {
     
    })
  },
  
  //审批提交
  approveForm(e){
    //避免表单重复提交-先禁用按钮
    this.setData({
      disabledApprove:true
    })
    let obj=e.detail.value;
    let td=this.data;
    let editInfo=td.editInfo; 
    let user = app.globalData.userInfo;
    //审批记录
      let approveRecordObj = {
        approver:{id:user.id,name:user.nickName},
        approveDate:util.timeFormat(new Date()),
        state:editInfo.state,
        text:user.nickName,
      }
      var desc = "" 
      //如果驳回，添加驳回理由
      if (editInfo.state === 1){
        approveRecordObj.reasonForRejection = editInfo.reasonForRejection 
        desc+= "驳回，"+editInfo.reasonForRejection+"-"+util.timeFormat(new Date())
      }else{
        desc+= "通过，"+util.timeFormat(new Date())
      }
      approveRecordObj.desc = desc;
      let approveRecord = []
      if (editInfo.approveRecord != null){
        approveRecord = editInfo.approveRecord
      }
      approveRecord.push(approveRecordObj)
      console.log(approveRecord);
    let param={
      className:'inspectionTaskList',
      data:{
        id: td.id,
        approveRecord:approveRecord,
      }
    }
    //如果审批通过移交下一个审批人
    if (editInfo.state === 2){
        // 找出当前审批人在审批列表的下表
          const index = this.data.editInfo.taskApprover.findIndex(
            approver => approver.id === user.id
          );
          console.log("下表",index);
          console.log("下表1",editInfo.currentApprover.level);
          console.log("下表2",editInfo.createLevel);
          if (editInfo.currentApprover.level == editInfo.createLevel){
            param.data.state = 3
            param.data.finishTaskDate = util.timeFormat(new Date());
          }
         
          if(this.data.editInfo.taskApprover.length>=index+1){
              const nextApprover = this.data.editInfo.taskApprover[index+1]
              param.data.currentApprover = nextApprover
              
          }
    }else{
      param.data.state = 1
    }
    console.log(param.data);
    console.log(this.data.paramObj)

    //避免表单重复提交
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '数据提交中...'
    });
    CommonService.goSave(param).then(res=>{
      this.setData({
        disabledApprove:false
      })
      if (res.statusCode == 200 && res.data.success == true){
        Toast.success('成功');
        setTimeout(() => {
          //返回列表页并刷新数据
          this.backAndRefresh();
        }, 1000);
      }else if(res.statusCode==202){
        Toast.fail('您操作太快了,请勿重复提交');
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })  
  },

  // 获取定位信息
  getLocationInfo() {
    let key=app.globalData.tencentKey;
    let address = ""
    return new Promise((resolve, reject) => {
      wx.getLocation({
        type: 'gcj02',
        success: (locationRes) => {
          const latitude = locationRes.latitude;
          const longitude = locationRes.longitude;
          console.log(latitude);
          console.log(longitude);
          // 可以在此处进行逆地理编码，将经纬度转换为具体地址
          wx.request({
            url: 'https://apis.map.qq.com/ws/geocoder/v1/',
            data: {
              location: `${latitude},${longitude}`,
              key: key
            },
            success: (res) => {
              console.log("地址数据")
              console.log(res);
              address = res.data.result.formatted_addresses.recommend;
              console.log("你的拍照地址");
              console.log(address);
              // 保存地址信息，用于后续添加水印
              //this.setData({ address });
              this.setData({
                location:address
              })
              resolve(address);
            }
          });
          resolve(address);
        },
        fail: (err) => {
          console.error('获取位置失败：', err);
        }
      });
     
    }).catch((error) => {
      resolve(null);
    });
 
  },


  //提交表单
   confirmForm(e){
    //避免表单重复提交-先禁用按钮
    this.setData({
      disabled:true
    })
    console.log(e);
    let obj=e.detail.value;
    let td=this.data;
    let editInfo=td.editInfo; 
    console.log("obj",obj);
    console.log("td",td);
    console.log("editInfo",editInfo);
    if(!td.mediaList||td.mediaList.length==0){
      Toast.fail('请上传拍摄照片');
      return;
    }   

    let param={
      className:'inspectionTaskList',
      data:{
        id: td.id,
        //处理详情及结果
        mediaList: td.mediaList
      }
    }
    //如果是确认按钮，只提交图片
    //确定并提交-修改状态，修改处理人，修改处理时间
    const buttonFlg = e.detail.target.dataset.flg;
    if (buttonFlg == "saveAndSubmit"){
        //提交后下一个状态是待审批2
        param.data.state=2,
        //处理人
        param.data.handler={id:this.data.user.id,name:this.data.user.nickName},
        param.data.completeDate=util.timeFormat(new Date())
    }
    

    console.log(param.data);
    console.log(this.data.paramObj);
    //避免表单重复提交
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '数据提交中...'
    });
    CommonService.goSave(param).then(res=>{
      this.setData({
        disabled:false
      })
      if (res.statusCode == 200 && res.data.success == true){
        Toast.success('成功');
        //生成审批流程
         if (buttonFlg == "saveAndSubmit" && td.editInfo.taskApprover==null){
          this.createApprover(td);
         }
        
        setTimeout(() => {
          //返回列表页并刷新数据
          this.backAndRefresh();
        }, 1000);
      }else if(res.statusCode==202){
        Toast.fail('您操作太快了,请勿重复提交');
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })  
  },

  createApprover(td){
    console.log("pppppppppppppppppppp");
    console.log(td);
    let data = {
      id:td.editInfo.id,
      authority:td.editInfo.dataAuthority.depart
    }
    console.log(data);
    CommonService.createApprover(data).then(res=>{

    })
  },


  //获取修改数据
  getInfo(){
    let param = {
      isAuth: false,
      className: 'inspectionTaskList',
      data: {
        id: this.data.id,
				selectFields: ['id','taskName','inspectionTaskId','project','taskType','taskDescribe','taskRequire','imgCountRequire','taskRange','createdUser','inspectionDate','state','img','completeDate','mediaList','dataAuthority','taskApprover','currentApprover','createLevel','approveRecord'],
				nbl: Base64.encode(util.timeFormatDay(new Date()))
      }
    }

    CommonService.goFindList(param).then(res => {
      console.log("res");
      console.log(res);
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
				let result=res.data.data.result[0];
				
        //创建时间
        if(result.submissionTime){
          result.self_submissionTime=util.timeFormat(result.submissionTime);
				}
				 //巡检时间
         if(result.inspectionDate){
          result.inspectionDate = result.inspectionDate.substring(0,10);
        }
        this.setData({
          editInfo: result,
          mediaList:result.mediaList==null?[]:result.mediaList
        })
      }
    }).catch((error) => {
    })
  },

  //非空验证（field要先去掉空格）
  formNotEmpty(field,messageField,messageCon){
    if(!field){
      let obj = {};
      obj[messageField] = messageCon;
      obj['disabled'] = true;
      this.setData(obj);
      return false;
    }else{
      return true;
    }
  },

  //用户输入时清除错误提示
  clearMessage(e) {
    console.log("0000000000000099999999999999999999999999");
    console.log(e);
    let field = e.target.dataset.message;
    let names = 'editInfo.'+field
    const value = e.detail;
     // 更新 initTaskObj.name
     this.setData({
      [names]: value
    });
  },  



  // 选择媒体文件（拍照）async
   chooseMedia() {
    this.checkPrivacyAndAuthStatus();
    // 计算还能选择多少张（最多9张）
    const remaining = 9 - this.data.mediaList.length;
    if (remaining <= 0) {
      wx.showToast({
        title: '最多只能选择9张照片',
        icon: 'none'
      });
      return;
    }
    
    const that = this;
    
    wx.chooseMedia({
      count: remaining,     // 最多选择的数量（剩余可选数量）
      mediaType: ['image'], // 只选择图片
      sourceType: ['camera'], // 只能拍照
      camera: 'back',       // 默认使用后置摄像头
      success(res) {
        console.log('选中的媒体文件：', res.tempFiles);
        
        // 为每个文件添加上传状态
        const newFiles = res.tempFiles.map(file => ({
          ...file,
          uploadStatus: 'pending', // pending: 待上传, uploading: 上传中, success: 成功, fail: 失败
          location: that.data.location
        }));
        
        // 将新选择的文件添加到列表中
        // that.setData({
        //   mediaList: [...that.data.mediaList, ...newFiles]
        // });
        that.setData({
          mediaList: [...that.data.mediaList, ...newFiles]
        }, () => {
          // 处理水印
          newFiles.forEach((file, index) => {
            that.addWatermarkToImage(
              file.tempFilePath,
              that.data.location,
              that.data.mediaList.length - newFiles.length + index
            );
          });
        });
      },
      fail(err) {
        console.error('选择媒体失败：', err);
        wx.showToast({
          title: '拍照失败',
          icon: 'none'
        });
      }
     
    });
    console.log(this.data);
  },


  // 为图片添加水印
  addWatermarkToImage(imagePath, location, index) {
    console.log("000000000000000000000000000");
    console.log(imagePath);
    console.log(location);
    console.log(index);
    const that = this;
    const query = wx.createSelectorQuery();
    
    query.select('#watermarkCanvas')
      .fields({ node: true, size: true })
      .exec((res) => {
        console.log("231");
        console.log(res);
        const canvas = res[0].node;
        const ctx = canvas.getContext('2d');
        
        // 创建图片对象
        const img = canvas.createImage();
        img.src = imagePath;
        
        img.onload = () => {
          // 设置canvas尺寸为图片尺寸
          canvas.width = img.width;
          canvas.height = img.height;
          
          // 绘制原图
          ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
          
          // 设置水印样式
          ctx.fillStyle = 'rgba(255, 255, 255, 0.8)'; // 白色半透明
          ctx.font = `bold ${Math.floor(canvas.width / 20)}px sans-serif`;
          ctx.textAlign = 'left';
          ctx.textBaseline = 'bottom';
          
          // 添加日期时间水印
          const date = new Date();
          const dateStr = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
          console.log(dateStr);
          // 绘制日期时间水印
          ctx.fillText(dateStr, 10, canvas.height - 50);
          
          // 绘制定位水印
          ctx.fillText(location, 10, canvas.height - 10);
          
          // 将canvas内容转为图片
          wx.canvasToTempFilePath({
            canvas: canvas,
            success: (res) => {
              console.log("----==--==--=-=--=-=-=-=-=");
              console.log(res);
              // 更新图片列表，添加上有水印的图片路径
              const newMediaList = [...that.data.mediaList];
              newMediaList[index].watermarkedPath = res.tempFilePath;
              newMediaList[index].uploadStatus = 'pending';
              
              that.setData({
                mediaList: newMediaList
              });
            },
            fail: (err) => {
              console.error('添加水印失败', err);
              wx.showToast({
                title: '添加水印失败',
                icon: 'none'
              });
            }
          });
        };
        
        img.onerror = (err) => {
          console.error('图片加载失败', err);
        };
      });
  },


// 删除选中的图片
deleteImage(e) {
  const index = e.currentTarget.dataset.index;
  const newList = [...this.data.mediaList];
  newList.splice(index, 1);
  this.setData({
    mediaList: newList
  });
},

    // 上传所有照片
    uploadAll() {
       // 筛选出待上传的图片
   const pendingFiles = this.data.mediaList.filter(file => file.uploadStatus === 'pending');
      this.setData({
        pendingFilesArr: pendingFiles
      })
   console.log("111111111222");
   console.log(this.data.mediaList);
   console.log(pendingFiles);
      // if (this.data.mediaList.length === 0) {
      //   wx.showToast({
      //     title: '请先拍摄照片',
      //     icon: 'none'
      //   });
      //   return;
      // }

      if (pendingFiles.length === 0) {
        wx.showToast({
          title: '没有待上传的图片',
          icon: 'none'
        });
        return;
      }
      
      if (this.data.isUploading) {
        wx.showToast({
          title: '正在上传中，请稍候',
          icon: 'none'
        });
        return;
      }
      
      // 初始化上传状态
      // this.setData({
      //   isUploading: true,
      //   showProgress: true,
      //   uploadProgress: 0,
      //   uploadedCount: 0,
      //   totalCount: this.data.mediaList.length
      // });

      this.setData({
        isUploading: true,
        showProgress: true,
        uploadProgress: 0,
        uploadedCount: 0,
        totalCount: this.data.pendingFilesArr.length
      });
      
      // 开始上传所有文件
      this.uploadFiles(0);
    },
// 递归上传文件
uploadFiles(index) {
  const that = this;
  const files = this.data.mediaList;
  let pendingFiles = this.data.pendingFilesArr;
   if (pendingFiles.length === 0) {
    wx.showToast({
      title: '没有待上传的图片',
      icon: 'none'
    });
    return;
  }
  // // 所有文件上传完成
  // if (index >= files.length) {
  //   this.setData({
  //     isUploading: false,
  //     uploadProgress: 100
  //   });
  // 所有文件上传完成
  if (index >= pendingFiles.length) {
    this.setData({
      isUploading: false,
      showProgress: false,
      uploadProgress: 0
    });
    wx.showToast({
      title: '所有文件上传完成',
      icon: 'success'
    });
    return;
  }

  // 找到当前文件在mediaList中的索引
  const mediaIndex = this.data.mediaList.findIndex(
    file => file.tempFilePath === pendingFiles[index].tempFilePath && 
           file.uploadStatus === 'pending'
  );
  console.log("mediaIndex");
  console.log(mediaIndex);
        if (mediaIndex === -1) {
          // 文件不存在，继续上传下一个
          this.uploadFiles(index + 1);
          return;
        }

        // 更新当前文件状态为上传中
        const newFiles = [...this.data.mediaList];
        newFiles[mediaIndex].uploadStatus = 'uploading';
        this.setData({
          mediaList: newFiles
        });
        index = mediaIndex
        console.log(index);
        console.log(files);
        // 2. 上传文件到OSS
        wx.uploadFile({
          url: app.globalData.ossUrl + 'headImgUpload?filepath=task/taskImg/', // OSS上传地址
          filePath: files[index].watermarkedPath,
          name: 'file', // 必须填file
          // 上传进度
          progress: (progressEvent) => {
            const percent = Math.round((progressEvent.loaded / progressEvent.total) * 100);
            // 计算总体进度
            const totalPercent = Math.round(
              (that.data.uploadedCount * 100 + percent) / that.data.totalCount
            );
            that.setData({
              uploadProgress: totalPercent
            });
          },
          success(uploadRes) {
            console.log("uploadRes");
            console.log(uploadRes);
            if (uploadRes.statusCode === 200) {
              // 上传成功
              //const fileUrl = ossSign.host + '/' + ossSign.key;
              console.log(`第${index+1}张上传成功:`);
              
              // 通知后端上传完成（可选）
              //that.notifyBackendComplete(ossSign.key, fileUrl);
              
              that.updateUploadStatus(index, 'success',uploadRes);
            } else {
              // 上传失败
              console.error(`第${index+1}张上传失败:`, uploadRes);
              that.updateUploadStatus(index, 'fail');
            }
          },
          fail(err) {
            console.error(`第${index+1}张上传失败:`, err);
            that.updateUploadStatus(index, 'fail');
          },
          complete() {
            // 继续上传下一张
            that.uploadFiles(index + 1);
          }
        });
},

// 更新上传状态
updateUploadStatus(index, status,uploadRes) {
  let imgUrl = JSON.parse(uploadRes.data).data; 
  if(imgUrl.indexOf("?")!=-1){
    let index = imgUrl.indexOf("?");
    if (index != -1) {
      imgUrl = imgUrl.substring(0, index); 
    }
  }   
  const newFiles = [...this.data.mediaList];
  newFiles[index].uploadStatus = status;
  newFiles[index].tempFilePath = imgUrl;
  newFiles[index].watermarkedPath = imgUrl;
  newFiles[index].uploadTime = util.timeFormat(new Date());
  
  let uploadedCount = this.data.uploadedCount;
  if (status === 'success') {
    uploadedCount++;
  }
  
  this.setData({
    mediaList: newFiles,
    uploadedCount: uploadedCount
  });
  console.log("this.data");
  console.log(this.data);
},

  //获取图片上传组件的传值
  getUploadUrl(data){
    let imgUrls=data.detail;
    if(imgUrls.length){
      let pic='editInfo.completionPic';
      this.setData({
        [pic]: imgUrls
      })
    }else{
			this.setData({
        [pic]: null
      })
		}

		this.setData({
			disabled: false
		})
  },

  //预览图片
  onPreviewImage(e) {
    let detail = e.target.dataset.detail;
    let src = e.target.dataset.src;
    console.log(e);
    // const details = detail.map(item => item.tempFilePath);
    // wx.previewImage({
    //   current: src.tempFilePath,
    //   urls: details
    // })

    const details = detail.map(item => item.watermarkedPath);
    wx.previewImage({
      current: src.watermarkedPath,
      urls: details
    })
  },

    //选择任务类型
    onchangetype(event){
      console.log("event")
      console.log(event)
      let taskType='editInfo.state';
      this.setData({
        [taskType]: parseInt(event.detail),
      })
      //如果驳回，显示驳回原因
      if(parseInt(event.detail) === 1){
          this.setData({
            showReasonForRejection:true
          })
      }else{
        this.setData({
          showReasonForRejection:false
        })
        let reasonForRejection='editInfo.reasonForRejection';
        this.setData({
          [reasonForRejection]: "",
        })
      }
  },

  //返回列表页并刷新数据
  backAndRefresh(){
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];

    prevPage.refreshListAndPage();
    wx.navigateBack();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})